package cn.hunqing.web.controller;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hunqing.web.dto.MyCardSimpleDto;
import cn.hunqing.web.dto.RestResponseWrapper;
import cn.hunqing.web.dto.TemplateSimpleDto;
import cn.hunqing.web.dto.WeddingInvitationCommentDto;
import cn.hunqing.web.dto.WeddingInvitationDto;
import cn.hunqing.web.param.MyCardParameters;
import cn.hunqing.web.param.TemplateParameters;
import cn.hunqing.web.service.PayCodeService;
import cn.hunqing.web.service.TemplateService;
import cn.hunqing.web.service.WeddingInvitationService;
import cn.hunqing.web.util.PathConstants;
import cn.hunqing.web.util.SessionUtils;
import cn.hunqing.web.util.ViewConstants;

/**
 * add the redirect method
 * 
 * @date 2015-07-27 21:12
 */
@Controller
@RequestMapping(PathConstants.PATH_MY_CARD)
public class WeddingInvitationController {
	private static Logger logger = LoggerFactory.getLogger(WeddingInvitationController.class);

	@Autowired
	private WeddingInvitationService weddingInvitationService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private PayCodeService payCodeService;
	
	@RequestMapping(value = "/{version}",method=RequestMethod.GET)
	public String doGetIndex(HttpServletRequest request, HttpSession httpSession,@PathVariable String version,ModelMap model) {
		logger.info("Get the my card index request");
		Integer userId = SessionUtils.getUserId(httpSession);
		logger.info("before enter my card page, current login user is "+userId);
		if(userId == null){
			return ViewConstants.VIEW_LOGIN;
		}
		List<MyCardSimpleDto> result = weddingInvitationService.getMyCards(userId);
		model.put(MyCardParameters.RESPONSE_CARDS, result);
		return ViewConstants.VIEW_MY_CARD;
	}

	@RequestMapping(value = "/{weddingInvitationId}/preview/{version}",method=RequestMethod.GET)
	public String doGetWeddingInvitationPreview(HttpServletRequest request, HttpSession httpSession, @PathVariable String weddingInvitationId,@PathVariable String version, ModelMap model) {
		logger.info("Get the wedding Invitation No:{} request",weddingInvitationId);
		weddingInvitationId = StringUtils.trim(weddingInvitationId);
		if(!StringUtils.isNumeric(weddingInvitationId)){
			return ViewConstants.VIEW_ERROR;
		}
		
		TemplateSimpleDto templateSimpleDto = weddingInvitationService.getTemplateByInvitationId(Integer.valueOf(weddingInvitationId));
		if(templateSimpleDto == null){
			return ViewConstants.VIEW_ERROR;
		}
		WeddingInvitationDto weddingInvitationDto = weddingInvitationService.getWeddingInvitationDto(Integer.valueOf(weddingInvitationId));
		model.addAttribute(TemplateParameters.RESPONSE_SELECTED_TEMPLATE, templateSimpleDto);
		model.addAttribute(MyCardParameters.RESPONSE_INVITATION_ID, weddingInvitationId);
		model.addAttribute("isPayed", weddingInvitationDto.getIsPayed());
		return ViewConstants.VIEW_PREVIEW;
	}
	
	@RequestMapping(value = "/{weddingInvitationId}/{version}",method=RequestMethod.GET)
	public String doGetWeddingInvitation(HttpServletRequest request, HttpSession httpSession, @PathVariable String weddingInvitationId,@PathVariable String version,ModelMap model) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		logger.info("Get the wedding Invitation No:{} request",weddingInvitationId);
		weddingInvitationId = StringUtils.trim(weddingInvitationId);
		if(!StringUtils.isNumeric(weddingInvitationId)){
			return ViewConstants.VIEW_ERROR;
		}

		int weddingInvitationIdInt = Integer.parseInt(weddingInvitationId);
		String templatePath = templateService.getTemplatePathByWeddingInvitationId(weddingInvitationIdInt);
		if(StringUtils.isEmpty(templatePath)){
			return ViewConstants.VIEW_ERROR;
		}
		WeddingInvitationDto weddingInvitationDto = weddingInvitationService.getWeddingInvitationDto(weddingInvitationIdInt);
		List<WeddingInvitationCommentDto> weddingInvitationComments = weddingInvitationService.getInvitationComments(weddingInvitationIdInt);
		model.put(MyCardParameters.RESPONSE_INVITATION, weddingInvitationDto);
		model.put("weddingInvitationComments", weddingInvitationComments);
		return String.format(ViewConstants.VIEW_TEMPLATE, templatePath);
	}
	
	@RequestMapping(value = "/{weddingInvitationId}/comments",method=RequestMethod.GET)
	public @ResponseBody RestResponseWrapper doGetWeddingInvitationComment(HttpServletRequest request, HttpSession httpSession, @PathVariable String weddingInvitationId,ModelMap model) {
		logger.info("Get the wedding Invitation Comments by No:{} request",weddingInvitationId);
		weddingInvitationId = StringUtils.trim(weddingInvitationId);
		if(!StringUtils.isNumeric(weddingInvitationId)){
			return RestResponseWrapper.error("错误的编号");
		}

		int weddingInvitationIdInt = Integer.parseInt(weddingInvitationId);
		
		List<WeddingInvitationCommentDto> comments = weddingInvitationService.getInvitationComments(weddingInvitationIdInt);
		return RestResponseWrapper.ok(comments);
	}
	
	@RequestMapping(value = "/{weddingInvitationId}/comments",method=RequestMethod.POST)
	public @ResponseBody RestResponseWrapper doPostWeddingInvitationComment(HttpServletRequest request, HttpSession httpSession, @PathVariable String weddingInvitationId,ModelMap model) {
		logger.info("Create new the wedding Invitation Comment for No:{} request",weddingInvitationId);
		weddingInvitationId = StringUtils.trim(weddingInvitationId);
		if(!StringUtils.isNumeric(weddingInvitationId)){
			return RestResponseWrapper.error("错误的编号");
		}

		int weddingInvitationIdInt = Integer.parseInt(weddingInvitationId);
		String commentName = request.getParameter(MyCardParameters.REQUEST_COMMENT_NAME);
		String commentValue = request.getParameter(MyCardParameters.REQUEST_COMMENT_VALUE);
		logger.info("Post the comment username:{}, value:{}",commentName, commentValue);
		if(StringUtils.isEmpty(commentName)){
			return RestResponseWrapper.error("请输入名字");
		}
		if(StringUtils.isEmpty(commentValue)){
			return RestResponseWrapper.error("请输入评论");
		}
		weddingInvitationService.createNewComment(weddingInvitationIdInt,commentName,commentValue);
		return RestResponseWrapper.ok(null);
	}
	@RequestMapping(value = "/{weddingInvitationId}/album/{version}",method=RequestMethod.GET)
	public String doGetWeddingInvitationAlbum(HttpServletRequest request, HttpSession httpSession, @PathVariable String weddingInvitationId,@PathVariable String version,ModelMap model) {
		logger.info("Create new the wedding Invitation album for No:{} request",weddingInvitationId);
		weddingInvitationId = StringUtils.trim(weddingInvitationId);
		if(!StringUtils.isNumeric(weddingInvitationId)){
			return ViewConstants.VIEW_ERROR;
		}

		int weddingInvitationIdInt = Integer.parseInt(weddingInvitationId);
		String templatePath = templateService.getTemplatePathByWeddingInvitationId(weddingInvitationIdInt);
		if(StringUtils.isEmpty(templatePath)){
			return ViewConstants.VIEW_ERROR;
		}
		WeddingInvitationDto weddingInvitationDto = weddingInvitationService.getWeddingInvitationDto(weddingInvitationIdInt);
		model.put(MyCardParameters.RESPONSE_PHOTOS, weddingInvitationDto.getWeddingPhotos());

		return String.format(ViewConstants.VIEW_ALBUM, templatePath);
	}
	
	@RequestMapping(value = "/{weddingInvitationId}/payByCode",method=RequestMethod.POST)
	public @ResponseBody RestResponseWrapper doPostWeddingInvitationPay(HttpServletRequest request, HttpSession httpSession, @PathVariable String weddingInvitationId,ModelMap model) {
		logger.info("Create new the wedding Invitation Comment for No:{} request",weddingInvitationId);
		Integer userId = SessionUtils.getUserId(httpSession);
		if(userId == null){
			return RestResponseWrapper.error("请先登录");
		}
		weddingInvitationId = StringUtils.trim(weddingInvitationId);
		if(!StringUtils.isNumeric(weddingInvitationId)){
			return RestResponseWrapper.error("错误的编号");
		}

		int weddingInvitationIdInt = Integer.parseInt(weddingInvitationId);
		String payCode = request.getParameter("payCode");
		logger.info("Post the payCode:{}",payCode);
		if(StringUtils.isEmpty(payCode)){
			return RestResponseWrapper.error("请输入支付码");
		}
		String queryPayCode = payCodeService.findByPayCode(payCode);
		if(StringUtils.isEmpty(queryPayCode)){
			return RestResponseWrapper.error("支付码错误");
		}
		weddingInvitationService.payByCode(weddingInvitationIdInt,payCode,userId);
		return RestResponseWrapper.ok(null);
	}
}
